package com.zzyl.framework.interceptor.impl;

import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取本次请求携带的令牌
        String token = request.getHeader("authorization");

        //如果令牌为空，直接返回401
        if (token == null ||"".equals(token)){
            response.setStatus(401);
            return false;
        }

        //解析令牌非法，直接返回401

        Claims claims =null;
        try {
             claims = tokenService.parseToken(token);
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }


        //解析令牌得到用户id，绑定到当前线程
        Long id = claims.get("id", Long.class);
        UserThreadLocal.set(id);


        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
